package com.qiku.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.qiku.dao.UserDao;
import com.qiku.dao.impl.UserDaoImpl;
import com.qiku.pojo.User;
import com.qiku.service.UserService;
import com.qiku.utils.DateUtils;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    @Override
    public User userLogin(String username, String password) {
        return userDao.userLogin(username, password);
    }

    @Override
    public String findAllUser() {
        List<User> allUser = userDao.findAllUser();
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(User.class);
        String s = JSON.toJSONString(allUser, filter);
        return s;
    }


    @Override
    public String findUserByName(String username) {
        User userByName = userDao.findUserByName(username);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(User.class, "username");
        String s = JSON.toJSONString(userByName, filter);
        return s;
    }

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @Override
    public String userRegister(User user) {
        //若 获取到的user对象  名字和密码不为空
        if (user.getUsername() != null && user.getPassword() != null) {
            //
            user.setUsername(user.getUsername().replaceAll(" ", ""));
            user.setPassword(user.getPassword().replaceAll(" ", ""));
            if (!"".equals(user.getUsername()) && !"".equals(user.getPassword())) {
                User userByName = userDao.findUserByName(user.getUsername());
                if (userByName == null) {
                    //补全信息
                    user.setRegister_date(DateUtils.getDateFormart());
                    int i = userDao.userRegister(user);
                    if (i > 0) {
                        //注册成功
                        return "success";
                    } else {
                        //注册失败  数据库插入出错
                        return "fail";
                    }
                } else {
                    //用户已存在
                    return "msg";
                }
            }else {
                //用户名和密码不能为空
                return "null";
            }
        } else {
            //用户名和密码不能为空
            return "null";
        }
    }

    /**
     * 管理员注销用户
     * @param id
     * @return
     */
    @Override
    public int destroyUser(int id) {
        return userDao.destroyUser(1,id);
    }

    /**
     * 管理员恢复用户
     * @param id 用户id
     * @return
     */
    @Override
    public int recoverUser(int id) {
        return userDao.destroyUser(0,id);
    }
}
